<template>
  <MainSlot v-loading="loading">
    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <div class="layout">
        <MenuEquipment :optionsList="menuoptionsList" @getMenuData="getMenuData"></MenuEquipment>
        <TableData v-if="resetTable" class="tableData" :config="table_config"
          :tableThead="selectIndex == 0 ? tableThead_dataItem : tableThead_camera" :dataList="dataList"
          :loading="loading" @selection-change="selectionChange">
          <template v-if="selectIndex == 0" v-slot:originalName="{ row }">
            {{ row.dataItem.originalName || '' }}
          </template>
          <template v-if="selectIndex == 0" v-slot:dataTypeName="{ row }">
            {{ row.dataItem.dataTypeName || '' }}
          </template>
          <template v-if="selectIndex == 1" v-slot:cameraName="{ row }">
            {{ row.camera.cameraName || '' }}
          </template>
          <template v-if="selectIndex == 1" v-slot:deviceSerial="{ row }">
            {{ row.camera.deviceSerial || '' }}
          </template>
        </TableData>
      </div>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size" @current-change="handleCurrentChange" :page="page"
        :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :title="initLabel + '设备'" @closeDialog="closeDialog" :deviceNo="deviceNo" :cameraList="cameraList"
        :selectIndex="selectIndex" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import AddEdit from './components/addEdit.vue';
import MenuEquipment from '@/components/NavMenu/menu_equipment.vue';
import deviceAllocationData from '@/api/basicInformation/deviceAllocationData'
import camera from '@/api/basicInformation/camera';


export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, AddEdit, MenuEquipment, EnumSlot },
  data() {
    return {
      deviceNo: '',
      loading: false,
      dialogVisible: false,
      resetTable: true,
      addEditFlag: 'add',
      formData: {},
      page: 1,
      size:10,
      total: 10,
      selectIndex: 0,
      btnList: ['add', 'delete'],
      deviceList: [],
      enumList: [{
        label: "分配数据项",
        type: 0
      },
      {
        label: "分配摄像头",
        type: 1
      }],
      menuoptionsList: [],
      dataList: [],
      cameraList: [],
      initLabel: '',
      tableThead_dataItem: [
        { isShow: true, label: '数据项名称', slotName: 'originalName' },
        { isShow: true, label: '数据类型', slotName: 'dataTypeName' }
      ],
      tableThead_camera: [
        { isShow: true, label: '摄像头名称', slotName: 'cameraName' },
        { isShow: true, label: '序列号', slotName: 'deviceSerial' }
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '删除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      }
    }
  },
  mounted() {
    this.queryDeviceList();
    this.getcameralist();
  },
  methods: {
    async getcameralist() {
      const { data } = await camera.getcameralist({})
      this.cameraList = data;
    },
    queryDeviceList() {
      deviceAllocationData.dataItemlist().then(res => {
        let data = res.data;
        this.deviceList = data;
        if (data.length > 0) {
          this.deviceNo = data[0].deviceNo;
        }
        this.changemenuoptionsList();
      });
    },
    //物联设备
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          deviceNo: this.deviceNo
        }
      }
      deviceAllocationData.datadevicelist(params).then(res => {
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    //摄像头
    queryPageByCondition_camera() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          deviceNo: this.deviceNo,
          organizationNo: sessionStorage.organizationNo,
          systemNo: "SC"
        }
      }
      deviceAllocationData.dataCameralist(params).then(res => {
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition_camera();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    changemenuoptionsList() {
      if (this.deviceList.length === 0) { return this.$message.warning("请先添加设备"); }
      this.$set(this.menuoptionsList, 0, {
        deviceName: "虚拟设备",
        isGroup: true,
        children: []
      });
      this.$set(this.menuoptionsList, 1, {
        deviceName: "物联设备",
        isGroup: true,
        children: []
      });
      this.deviceList.forEach(item => {
        if (item.type === "VIRTUAL") {
          this.menuoptionsList[0].children.push(item);
          this.menuoptionsList[0].deviceName = "虚拟设备";
          this.menuoptionsList[0].deviceNo = this.menuoptionsList[0].children[0].deviceNo;
          this.menuoptionsList[0].disabled = true;
        } else if (item.type === "IOT") {
          this.menuoptionsList[1].children.push(item);
          this.menuoptionsList[1].deviceName = "物联设备";
          this.menuoptionsList[1].disabled = true;
          this.menuoptionsList[1].deviceNo = this.menuoptionsList[1].children[0].deviceNo;
        }
      });
      console.log(this.menuoptionsList)
    },
    getMenuData(data) {
      this.initLabel = data.isGroup ? '' : data.deviceName;
      this.deviceNo = data.deviceNo || '-1';
      this[this.selectIndex == 0 ? 'queryPageByCondition' : 'queryPageByCondition_camera']();
      console.log(data)
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      this.page = 1;
      this.dataList = [];
      this.selectIndex = enumInfo.index || 0;
      this[this.selectIndex == 0 ? 'queryPageByCondition' : 'queryPageByCondition_camera']();
      this.resetTable = false;
      this.$nextTick(() => {
        this.resetTable = true;
      })
    },
    handleCurrentChange(page) {
      this.page = page;
      this[this.selectIndex == 0 ? 'queryPageByCondition' : 'queryPageByCondition_camera']();
    },

    handleSizeChange(size) {
      this.size = size;
      this[this.selectIndex == 0 ? 'queryPageByCondition' : 'queryPageByCondition_camera']();
    },
    // 操作方法
    handleRow(rowData, item) {
      console.log(rowData, item);
      if (item.flag == 'delete') {
        this.delList([rowData])
      }
      this.addEditFlag = item.flag
    },// 多选方法
    selectionChange(val) {
      this.selectList = val;
    },
    delList(deleteList = []) {
      let list = []
      let delKey = this.selectIndex == 0 ? 'deviceDataItemMapperId' : 'deviceCameraMapperId'
      deleteList.forEach(item => {
        list.push(item[delKey])
      })
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = {}
        if (this.selectIndex == 0) {
          res = await deviceAllocationData.delListFarmingTypelist({ deviceDataItemMapperIdList: list });
        } else {
          res = await deviceAllocationData.CameraDelList({ deviceCameraMapperIdList: list })
        }
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this[this.selectIndex == 0 ? 'queryPageByCondition' : 'queryPageByCondition_camera']();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        if (this.initLabel) {
          this.dialogVisible = true;
        } else {
          this.$message.warning('请选择设施')
        }
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this[this.selectIndex == 0 ? 'queryPageByCondition' : 'queryPageByCondition_camera']();
    },
  }
};
</script>
<style lang="scss" scoped>
.layout {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;

  .tableData {
    width: calc(100% - 300px);
    height: 100%;
  }
}
</style>